
<template>
  <a-modal
      title="审批确认"
      :width="700"
      :open="visibleFlag"
      @cancel="onClose"
      :maskClosable="false"
      :destroyOnClose="true"
  >
       <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 5 }">
      <a-form-item label="采购日期" name="purchaseDate">
        <a-date-picker  show-time valueFormat="YYYY-MM-DD HH:mm:ss" v-model:value="form.purchaseDate" style="width: 100%"
                       placeholder="采购日期" disabled/>
      </a-form-item>
      <a-form-item label="请购部门" name="department">
        <a-input style="width: 100%" v-model:value="form.department" placeholder="请购部门"  disabled/>
      </a-form-item>
      <a-form-item label="申请人" name="applicant">
<!--        <a-input style="width: 100%" v-model:="formState.managerId" placeholder="申请人"/>-->
          <EmployeeSelect ref="employeeSelect" placeholder="请选择部门负责人" width="100%" v-model:value="form.actualName"   :showDepartment="false" @send:Department="getDepartment" disabled/>


      </a-form-item>
      <a-form-item label="申请人电话" name="applicantPhone">
        <a-input style="width: 100%" v-model:value="form.applicantPhone" placeholder="申请人电话"  disabled/>
      </a-form-item>
      <a-form-item label="耗材名称" name="materialName">
        <a-input style="width: 100%" v-model:value="form.materialName" placeholder="耗材名称" disabled/>
      </a-form-item>
         <a-form-item label="耗材编码" name="materialCode">
           <a-input style="width: 100%" v-model:value="form.materialCode" placeholder="耗材编码" disabled/>
         </a-form-item>
         <a-form-item label="类型" name="category">
           <!--        <a-input style="width: 100%" v-model:value="form.category" placeholder="耗材类别"/>-->
           <CategoryTree v-model:value="form.category" placeholder="请选择商品分类"
                         :categoryType="CATEGORY_TYPE_ENUM.category.value" disabled/>
         </a-form-item>
      <a-form-item label="规格" name="specification">
        <a-input style="width: 100%" v-model:value="form.specification" placeholder="规格" disabled/>
      </a-form-item>
         <a-form-item label="单位" name="unit">
           <a-input style="width: 100%" v-model:value="form.unit" placeholder="单位" disabled/>
         </a-form-item>
      <a-form-item label="数量" name="quantity">
        <a-input-number style="width: 100%" v-model:value="form.quantity" placeholder="数量" disabled/>
      </a-form-item>
      <a-form-item label="单价（元）" name="unitPrice">
        <a-input-number style="width: 100%" v-model:value="form.unitPrice" placeholder="单价（元）" disabled/>
      </a-form-item>

      <a-form-item label="金额（元）" name="totalAmount">
        <a-input-number style="width: 100%" v-model:value="form.totalAmount" placeholder="金额（元）" disabled/>
      </a-form-item>
      <a-form-item label="存放地点" name="storageLocation">
        <a-input style="width: 100%" v-model:value="form.storageLocation" placeholder="存放地点" disabled/>
      </a-form-item>
         <a-form-item label="采购途径" name="purchaseChannel">
           <a-input style="width: 100%" v-model:value="form.purchaseChannel" placeholder="采购途径" disabled/>
         </a-form-item>
      <a-form-item label="预算采购金额（元）" name="budgetAmount">
        <a-input-number style="width: 100%" v-model:value="form.budgetAmount" placeholder="预算采购金额（元）" disabled/>
      </a-form-item>
      <a-form-item label="经费项目名称" name="projectName">
        <a-input style="width: 100%" v-model:value="form.projectName" placeholder="经费项目名称" disabled/>
      </a-form-item>
      <a-form-item label="经费项目编号" name="projectId">
        <a-input style="width: 100%" v-model:value="form.projectId" placeholder="经费项目编号" disabled/>
      </a-form-item>
      <a-form-item label="使用部门副职意见" name="deputyHeadOpinion"
                   v-privilege="'consum:input:query'"  v-if="userInfo.positionId == positionIdFu || userStore.positionId == positionIdSuper">
        <a-input  v-if="userStore.positionId == positionIdSuper" style="width: 100%" v-model:value="opinionText(form.deputyHeadOpinion).value"
                 placeholder="使用部门副职意见" disabled/>
        <a-radio-group v-model:value="form.deputyHeadOpinion" v-else>
          <a-radio :value="0">不同意</a-radio>
          <a-radio :value="1">同意</a-radio>
        </a-radio-group>

      </a-form-item>
      <a-form-item label="使用部门正职意见" name="headOpinion"
                   v-privilege="'consum:input:query'"  v-if="userInfo.positionId == positionId || userStore.positionId == positionIdSuper">
        <a-input  v-if="userStore.positionId == positionIdSuper" style="width: 100%" v-model:value="opinionText(form.headOpinion).value"
                 placeholder="使用部门正职意见" disabled/>
        <a-radio-group v-model:value="form.headOpinion" v-else>
          <a-radio :value="0">不同意</a-radio>
          <a-radio :value="1">同意</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item v-if="moneyShow && (userStore.positionId == positionIdZhi || userStore.positionId == positionIdSuper) " label="职能部门意见（大于2万元，包括签名和日期）0表示不同意 1表示同意" name="functionDepartmentOpinion"
                   v-privilege="'consum:input:query'" >

        <a-input style="width: 100%" v-model:value="form.functionDepartmentOpinion" v-if="userStore.positionId == positionIdSuper"
                 placeholder="职能部门意见（大于2万元，包括签名和日期）0表示不同意 1表示同意"/>
        <a-radio-group v-model:value="form.functionDepartmentOpinion" v-else>
          <a-radio :value="0">不同意</a-radio>
          <a-radio :value="1">同意</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item v-if="moneyShow &&  (userStore.positionId == positionIdTea || userStore.positionId == positionIdSuper)" label="教学主管领导意见（大于2万元，包括签名和日期）0表示不同意 1表示同意" name="teachingLeaderOpinion"
                   v-privilege="'consum:input:query'">
        <a-input v-if="userStore.positionId == positionIdSuper" style="width: 100%" v-model:value="form.teachingLeaderOpinion"
                 placeholder="教学主管领导意见（大于2万元，包括签名和日期）0表示不同意 1表示同意"/>
        <a-radio-group v-model:value="form.teachingLeaderOpinion" v-else>
          <a-radio :value="0">不同意</a-radio>
          <a-radio :value="1">同意</a-radio>
        </a-radio-group>
      </a-form-item>
<!--      <a-form-item label="审核状态，pending表示待审核，approved表示已批准，rejected表示已拒绝" name="approvalStatus"-->
<!--                   v-privilege="'consum:input:query'">-->
<!--        <a-input style="width: 100%" v-model:value="form.approvalStatus"-->
<!--                 placeholder="审核状态，pending表示待审核，approved表示已批准，rejected表示已拒绝"/>-->
<!--      </a-form-item>-->
<!--         添加审批-->
          <a-form-item label="审核状态" name="approvalStatus"  v-privilege="'consumablesPurchaseApproval:approval'">
            <a-select v-model:value="form.approvalStatus" placeholder="请选择" style="width: 100%" :options="approvalOption">
            </a-select>
          </a-form-item>
    </a-form>

    <template #footer>
      <a-space>
        <a-button @click="onClose">取消</a-button>
        <a-popconfirm
            title="信息确认完毕?"
            ok-text="Yes"
            cancel-text="No"
            @confirm="onSubmit"
        >
          <a-button type="primary" v-if="validPosition">审批</a-button>
        </a-popconfirm>

      </a-space>
    </template>
  </a-modal>

</template>
<script setup>
import {reactive, ref, nextTick, toRefs, onMounted, computed, watch, watchEffect} from 'vue';
import _ from 'lodash';
import { message } from 'ant-design-vue';
import { SmartLoading } from '/@/components/framework/smart-loading';
import { consumablesInventoryApi } from '/@/api/business/consumables-inventory/consumables-inventory-api';
import { smartSentry } from '/@/lib/smart-sentry';
import EmployeeSelect from '/@/components/system/employee-select/index.vue';
import {useUserStore} from "/@/store/modules/system/user.js";
import {fabricMaterialsApi} from "/@/api/business/fabric-materials/fabric-materials-api.js";
import {
  consumablesPurchaseApprovalApi
} from "/@/api/business/consumables-purchase-approval/consumables-purchase-approval-api.js";
import CategoryTree from '/@/components/business/category-tree-select/index.vue';

// ------------------------ 事件 ------------------------

const emits = defineEmits(['reloadList']);

const userInfo = useUserStore();

const acceptUser = userInfo.actualName;
//使用部部长
const positionId = ref(8)
//使用部副部长
const positionIdFu = ref(9)
//教学主管
const positionIdTea = ref(21)
//职能部门
const positionIdZhi = ref(19)
//超管
const positionIdSuper = ref(11)

const approvalOption = ref([{
  label: '未审批',
  value: 0,
  disabled: true,
}, {
  label: '通过',
  value: 1
}, {
  label: '驳回',
  value: 2
}])
const CATEGORY_TYPE_ENUM = {
  category: {
    value: 2,
    desc: '类别',
  },
}
// ------------------------ 显示与隐藏 ------------------------
// 是否显示
const visibleFlag = ref(false);

function show(rowData) {
  Object.assign(form, formDefault);
  if (rowData && !_.isEmpty(rowData)) {
    Object.assign(form, rowData);
  }
  form.inspectorActualName =  acceptUser;

  // console.log('accpetUser',acceptUser)
  // 使用字典时把下面这注释修改成自己的字典字段 有多个字典字段就复制多份同理修改 不然打开表单时不显示字典初始值
  // if (form.status && form.status.length > 0) {
  //   form.status = form.status.map((e) => e.valueCode);
  // }
  visibleFlag.value = true;
  nextTick(() => {
    formRef.value.clearValidate();
  });
}

function onClose() {
  Object.assign(form, formDefault);
  visibleFlag.value = false;
}





const opinionText  =  (item) => {
 return  computed(()=>{
    switch (item) {
      case 0:
        return '已驳回';
      case 1:
        return '已通过';
      default:
        return '未审批';
    }
  })
}

onMounted(()=>{

})

// ------------------------ 表单 ------------------------

// 组件ref
const formRef = ref();
const employeeSelect = ref();
const defaultDepartmentForm = {
  managerId: undefined, //部门负责人
};
const userStore = useUserStore();
const moneyShow = ref(false);


let formState = reactive({
  ...defaultDepartmentForm,
});


const formDefault = {
  id:undefined,
  purchaseDate: undefined, //采购日期
  department: undefined, //请购部门
  applicant: undefined, //申请人
  actualName:undefined,
  applicantPhone: undefined, //申请人电话
  serialNumber: undefined, //序号
  materialName: undefined, //耗材名称
  specification: undefined, //规格
  quantity: undefined, //数量
  unitPrice: undefined, //单价（元）
  totalAmount: undefined, //金额（元）
  storageLocation: undefined, //存放地点
  budgetAmount: undefined, //预算采购金额（元）
  projectName: undefined, //经费项目名称
  projectId: undefined, //经费项目编号
  approvalStatus: undefined, //审核状态
  deputyHeadOpinion: undefined, //使用部门副职意见（包括签名和日期）0表示不同意 1表示同意
  headOpinion: undefined, //使用部门正职意见（包括签名和日期）0表示不同意 1表示同意
  functionDepartmentOpinion: undefined, //职能部门意见（大于2万元，包括签名和日期）0表示不同意 1表示同意
  teachingLeaderOpinion: undefined, //教学主管领导意见（大于2万元，包括签名和日期）0表示不同意 1表示同意
  category:undefined,
  unit:undefined,
  purchaseChannel:undefined,
  materialCode:undefined
};

let form = reactive({ ...formDefault });

const rules = {


};





// 点击确定，验证表单
async function onSubmit() {
  try {
    save();
  } catch (err) {
    message.error('参数验证错误，请仔细填写表单数据!');
  }
}
const {approvalStatus,deputyHeadOpinion,headOpinion,teachingLeaderOpinion,functionDepartmentOpinion} = toRefs(form);
// 新建、编辑API
const validPosition = computed(() =>{
  switch (userInfo.positionId) {
    case positionIdFu.value:
      return deputyHeadOpinion.value != null;
    case positionId.value:
      return headOpinion.value!= null;
    case positionIdTea.value:
      return teachingLeaderOpinion.value!= null;
    case positionIdZhi.value:
      return functionDepartmentOpinion.value!= null;
    case positionIdSuper.value:
      return approvalStatus.value!= 0;
    default:
      return false;
  }

})


async function save() {
  SmartLoading.show();
  let purchaseApproval = {
    id: form.id,
    approvalStatus: form.approvalStatus ,  // Default to 0 if not present
    purchaseChannel: form.purchaseChannel ,
    purchaseDate: form.purchaseDate ,
    applicant: form.applicant ,
    materialName: form.materialName ,
    specification: form.specification ,
    quantity: form.quantity ,
    unitPrice: form.unitPrice ,
    totalAmount: form.totalAmount ,
    storageLocation: form.storageLocation ,
    deputyHeadOpinion: form.deputyHeadOpinion ,
    headOpinion: form.headOpinion ,
    functionDepartmentOpinion: form.functionDepartmentOpinion ,
    teachingLeaderOpinion: form.teachingLeaderOpinion ,
    unit:form.unit,
    category:form.category,
    materialCode:form.materialCode
  };

  try {
    if (form.id) {
      await consumablesPurchaseApprovalApi.approval(purchaseApproval);
    }
    message.success('操作成功');
    emits('reloadList');
    onClose();
  } catch (err) {
    smartSentry.captureError(err);
  } finally {
    SmartLoading.hide();
  }
}
watch(()=>form.budgetAmount,(val)=>{
  // console.log('val',val)
  if (Number(val)  > 20000 ) {
    moneyShow.value = true
  }else {
    moneyShow.value = false
  }
},{immediate:true,deep:true})
defineExpose({
  show,
});


</script>
